package com.ruoyi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.domain.entity.*;
import com.ruoyi.project.domain.query.ProjectQuery;
import com.ruoyi.project.mapper.ProjectAllocationDetailMapper;
import com.ruoyi.project.mapper.ProjectAllocationMapper;
import com.ruoyi.project.mapper.ProjectDetailLogMapper;
import com.ruoyi.project.mapper.ProjectFeeMapper;
import com.ruoyi.project.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.xmlbeans.impl.xb.xsdschema.All;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;


@Service
public class ProjectAllocationDetailServiceImpl extends ServiceImpl<ProjectAllocationDetailMapper, AllocationDetail> implements IProjectAllocationDetailService {
    @Resource
    private ProjectFeeMapper projectFeeMapper;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private IProjectParticipanService personService;

    @Resource
    private IProjectGjpUserService projectGjpUserService;

    @Resource
    private IProjectService projectService;

    @Resource
    ISysDictDataService dictDataService;

    @Resource
    IProjectAllocationService allocationService;

    @Resource
    private IProjectAllocationDetailService detailService;

    @Resource
    private IProjectAccountingService accountingService;

    @Resource
    private IProjectPhaseService phaseService;

    @Resource
    ProjectAllocationDetailMapper detailMapper;

    @Resource
    ProjectDetailLogMapper projectDetailLogMapper;

    @Override
    public boolean updateAllocationDetail(AllocationDetail detail, boolean flag) {
        //验收阶段 没有提成 不需要计算
        if (flag) {
            return detailService.updateById(detail);
        }

        //1.通过父id获取岗位的标准绩效系数和标准岗位绩效金额  计算该岗位有多少可分配 先分配其他人的 销售负责人的最后减去其他人已分配的
        LambdaQueryWrapper<ProjectAllocation> allocationWrapper = new LambdaQueryWrapper<ProjectAllocation>();
        allocationWrapper.eq(ProjectAllocation::getId, detail.getAllocationId());
        allocationWrapper.eq(ProjectAllocation::getCurrent, detail.getCurrent());
        ProjectAllocation allocation = allocationService.getById(detail.getAllocationId());
        //标准岗位绩效金额  如果应该岗位有多个人 需要除以人数

        //先查询该岗位下有多少个人

        LambdaQueryWrapper<AllocationDetail> detailWrapper = new LambdaQueryWrapper<AllocationDetail>();
        detailWrapper.eq(AllocationDetail::getAllocationId, detail.getAllocationId());
        detailWrapper.eq(AllocationDetail::getCurrent, detail.getCurrent());
        List<AllocationDetail> list = detailService.list(detailWrapper);
        int count = 1;

        if (!list.isEmpty()) {
            count = list.size();
        }

        allocation.getDetailList();

        //绩效金额应该要除以人数
        BigDecimal allocationMoney = allocation.getMoney();
        allocationMoney = allocationMoney.divide(new BigDecimal(count));
        //销售负责人的绩效等于可被分配的金额减去各个参与人的绩效金额之和
        //如果不是销售负责人  先获取可分配金额  与计算的当前金额进行比较
        if (detail.getRatio() != null && detail.getRatio().compareTo(new BigDecimal("200")) > 0) {
            throw new RuntimeException("绩效系数不能超过200,请重新打分");
        }

        //先获取可分配的金额
        Map<String, BigDecimal> allocationInfo = getAllocationInfo(detail.getProjectNo(), detail.getCurrent());
        allocationInfo.get("allCommission");//总的
        allocationInfo.get("already");//已分配的
        BigDecimal remaining1 = allocationInfo.get("remaining");//可分配的
        //销售负责人的
        BigDecimal saleMoney = allocationInfo.get("saleMoney");
        BigDecimal remainingAndSale = BigDecimal.ZERO;
        if (saleMoney.compareTo(BigDecimal.ZERO) > 0) {
            remainingAndSale = remaining1.add(saleMoney);//把销售负责人的加入到可分配中
        } else {
            remainingAndSale = remaining1.add(saleMoney);//质保金没收回来 现在是亏损状态 是负数
        }
        // 计算： 标准岗位绩效金额 * 对应的打分的绩效系数 / 100 可能会超出(意味着最后销售负责人的绩效减少) 最后还要更新销售负责人的绩效
        BigDecimal saleCurrentDetailMoney = allocationMoney.multiply(detail.getRatio()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);

        //比较可分配的和当前正常计算的绩效金额  如果正常金额saleCurrentDetailMoney大于可分配的 就使用可分配的 如果正常的金额小于可分配的就用正常的

        BigDecimal result = BigDecimal.ZERO;
        if (saleCurrentDetailMoney.compareTo(remainingAndSale) > 0 && saleMoney.compareTo(BigDecimal.ZERO) > 0) {
            // 正常计算金额大于可分配金额：使用可分配的 (这里的可分配已加上销售负责人的)
            result = remainingAndSale;
        } else {
            // 正常计算金额 <= 可分配金额：使用正常金额
            result = saleCurrentDetailMoney;
        }


        detail.setMoney(result);
        //如果超过了标准绩效金额 从销售负责人的绩效金额扣除

        //设置个人绩效
        String personAllocation = dictDataService.selectDictLabel("allocation_type", "1");
        BigDecimal personAllocationMoney = result.multiply(new BigDecimal(personAllocation));
        detail.setPersonMoney(personAllocationMoney);

        //设置部门绩效
        String deptAllocation = dictDataService.selectDictLabel("allocation_type", "2");
        BigDecimal deptAllocationMoney = result.multiply(new BigDecimal(deptAllocation));
        detail.setDeptMoney(deptAllocationMoney);
        return detailService.updateById(detail);

    }

    @Override
    public Map<String, BigDecimal> getAllocationInfo(String projectNo, String current) {
        Map<String, BigDecimal> map = new HashMap<>();
        //记录已分配的
        BigDecimal alreadyAllocationMoney = BigDecimal.ZERO;
        if ("1".equals(current)) {

            //查询所有岗位的绩效信息
            LambdaQueryWrapper<AllocationDetail> detailListWrapper = new LambdaQueryWrapper<AllocationDetail>();
            detailListWrapper.eq(AllocationDetail::getProjectNo, projectNo);
            detailListWrapper.eq(AllocationDetail::getCurrent, current);

            List<AllocationDetail> detailLis = detailService.list(detailListWrapper);
            //累加所有的已分配的绩效金额
            for (AllocationDetail currAllocationDetail : detailLis) {
                alreadyAllocationMoney = alreadyAllocationMoney.add(currAllocationDetail.getMoney());
            }

            //
            LambdaQueryWrapper<ProjectAllocation> allocationWrapper = new LambdaQueryWrapper<ProjectAllocation>();
            allocationWrapper.eq(ProjectAllocation::getProjectNo, projectNo);
            allocationWrapper.eq(ProjectAllocation::getPostId, 5L);
//            allocationWrapper.eq(ProjectAllocation::getCurrent, current);
            //查询出销售负责人的当前绩效金额
            BigDecimal saleMoney = BigDecimal.ZERO;
            try {
//                ProjectAllocation projectAllocation = allocationService.getOne(allocationWrapper);

                List<ProjectAllocation> listSalePerson = allocationService.list(allocationWrapper);

                for (ProjectAllocation personSale : listSalePerson) {
                    saleMoney = saleMoney.add(personSale.getMoney() != null ? personSale.getMoney() : BigDecimal.ZERO);
                }

//                if (projectAllocation != null) {
//                    saleMoney = projectAllocation.getMoney();
//                }
            } catch (RuntimeException e) {
                throw new RuntimeException("后端接口错误，请联系管理员");
            }


            //使用项目提成金额减去已分配的 得到剩余可分配的
            Map<String, BigDecimal> allCommissionMap = accountingService.getAllList(projectNo);
            BigDecimal allCommission = allCommissionMap.get("allCommission");
            BigDecimal remaining = allCommission.subtract(alreadyAllocationMoney);
            map.put("allCommission", allCommission);//总的
            map.put("already", alreadyAllocationMoney);//已分配的
            map.put("remaining", remaining);//可分配的
            map.put("saleMoney", saleMoney);//销售负责人的
            confirmMoney(map, projectNo, current);
            //判断总的和已分配的是否相等 误差允许在一块钱以内 BigDecimal类型
//            allCommission alreadyAllocationMoney
            if (allCommission != null || alreadyAllocationMoney != null) {
                // 计算差值：总的 - 已分配
                BigDecimal diff = allCommission.subtract(alreadyAllocationMoney);

                // 设置允许的最大误差为 1 元
                BigDecimal tolerance = new BigDecimal("1.00");

                // 判断差值是否在 [-1, +1] 范围内
                // 即：-1 <= diff <= 1
                boolean result = diff.compareTo(tolerance) <= 0 && diff.compareTo(tolerance.negate()) >= 0;
//                    map.put("compare", result);
            }
            return map;

        } else {

            //查询所有岗位的绩效信息
            LambdaQueryWrapper<AllocationDetail> detailListWrapper = new LambdaQueryWrapper<AllocationDetail>();
            detailListWrapper.eq(AllocationDetail::getProjectNo, projectNo);
            detailListWrapper.eq(AllocationDetail::getCurrent, current);

            List<AllocationDetail> detailLis = detailService.list(detailListWrapper);
            //累加所有的已分配的绩效金额
            for (AllocationDetail currAllocationDetail : detailLis) {
                alreadyAllocationMoney = alreadyAllocationMoney.add(currAllocationDetail.getMoney());
            }

            //
            LambdaQueryWrapper<ProjectAllocation> allocationWrapper = new LambdaQueryWrapper<ProjectAllocation>();
            allocationWrapper.eq(ProjectAllocation::getProjectNo, projectNo);
            allocationWrapper.eq(ProjectAllocation::getPostId, 5L);
//            allocationWrapper.eq(ProjectAllocation::getCurrent, current);
            //查询出销售负责人的当前绩效金额
            BigDecimal saleMoney = BigDecimal.ZERO;
            try {
                ProjectAllocation projectAllocation = allocationService.getOne(allocationWrapper);
                saleMoney = projectAllocation.getMoney();
            } catch (RuntimeException e) {
                throw new RuntimeException("后端接口错误，请联系管理员");
            }


            //使用项目提成金额减去已分配的 得到剩余可分配的
            Map<String, BigDecimal> allCommissionMap = accountingService.getAllList(projectNo);
            BigDecimal allCommission = allCommissionMap.get("allCommissionWarranty");
            BigDecimal remaining = allCommission.subtract(alreadyAllocationMoney);
            map.put("allCommission", allCommission);//总的
            map.put("already", alreadyAllocationMoney);//已分配的
            map.put("remaining", remaining);//可分配的
            map.put("saleMoney", saleMoney);//销售负责人的
            confirmMoney(map, projectNo, current);
            return map;
        }
    }

    public void confirmMoney(Map<String, BigDecimal> map, String projectNo, String current) {
        BigDecimal confirmTotal = BigDecimal.ZERO;
        BigDecimal confirmRemaining = BigDecimal.ZERO;
        //所有的个人绩效
        BigDecimal personTotal = BigDecimal.ZERO;
        //查询已发放为未发放的
        LambdaQueryWrapper<AllocationDetail> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(AllocationDetail::getProjectNo, projectNo);
        detailWrapper.eq(AllocationDetail::getCurrent, current);
        List<AllocationDetail> detailList = detailService.list(detailWrapper);
        for (AllocationDetail detail : detailList) {
            confirmTotal = confirmTotal.add(detail.getAlready() != null ? detail.getAlready() : BigDecimal.ZERO);
            personTotal = personTotal.add(detail.getPersonMoney());
        }
        map.put("confirmTotal", confirmTotal);

        //总的个人绩效减去已发放的
        confirmRemaining = personTotal.subtract(confirmRemaining);

        map.put("confirmRemaining", confirmRemaining);
    }

    @Override
    public Map<String, Object> getAuditPermission(String projectNo, String current) {
        Map<String, Object> map = new HashMap<>();
        //查询还要哪些人未确认分配的  除去销售负责人
        //查询所有岗位的绩效信息
        //已分配的 分为项目经理 和其他人
        // 项目经理由销售负责人分配 需要查询项目经理的Audit有没有包含5 和 13  5.17改 工程售前也属于销售负责人分配
        // 其他人由项目经理分配  需要查询audit有没有包含2

        LambdaQueryWrapper<AllocationDetail> detailListWrapper = new LambdaQueryWrapper<AllocationDetail>();
        detailListWrapper.eq(AllocationDetail::getProjectNo, projectNo);
        List<AllocationDetail> detailList = detailService.list(detailListWrapper);

        String resultStr = "";
        boolean flag = true;
        Long userId = SecurityUtils.getUserId();
        //如果是总经理
        if (userId.equals(100L)) {
            for (AllocationDetail detail : detailList) {

                //查询父项 销售负责人不需要确认
                Long allocationId = detail.getAllocationId();
                ProjectAllocation allocation = allocationService.getById(allocationId);
                if (allocation != null && allocation.getPostId() == 5L) {
                    continue;
                }

                List<Integer> audit = detail.getAudit();
                if (audit == null) {
                    audit = new ArrayList<>();
                }
                if (audit.contains(100)) {
                    System.out.println("总经理已确认的");
                } else {
                    System.out.println("列表不包含100的");
                    resultStr = detail.getPersonName() + "的绩效还未确认分配,请确认";
                    flag = false;
                    break;
                }
            }
        } else { //说明是验收环节的分配
            for (AllocationDetail detail : detailList) {

                //查询父项 是否是销售负责人  过滤掉
                Long allocationId = detail.getAllocationId();
                ProjectAllocation allocation = allocationService.getById(allocationId);
                if (allocation != null && allocation.getPostId() == 5L) {
                    continue;
                }

                List<Integer> audit = detail.getAudit();
                if (audit == null) {
                    audit = new ArrayList<>();
                }
                if (audit.contains(2) || audit.contains(5)) {
                    // 列表包含2或5
                    System.out.println("列表包含2或5");
                } else {
                    // 列表不包含2或5
                    System.out.println("列表不包含2或5");
                    resultStr = detail.getPersonName() + "的绩效还未确认分配，" + "等待" + allocation.getRemark() + "确认";
                    flag = false;
                    break;
                }
            }
        }

        if (detailList == null || detailList.size() == 0) {
            flag = false;
            resultStr = "请先点击绩效分配按钮分配绩效";
        }

        // 项目验收环节结束 批量设置截止日期为项目验收日期
        if (!userId.equals(100L) && flag) {
            for (AllocationDetail detail : detailList) {
                detail.setEndDate(new Date());
            }
            detailService.updateBatchById(detailList);
        }


        map.put("flag", flag);
        map.put("msg", resultStr);
        return map;
    }


    @Override
    public boolean auditAllocation(String projectNo, String current) {

        Long userId = SecurityUtils.getUserId();

        LambdaQueryWrapper<ProjectAllocation> allocationWrapperList = new LambdaQueryWrapper<ProjectAllocation>();
        allocationWrapperList.eq(ProjectAllocation::getProjectNo, projectNo);
        //绩效系数两个阶段是一样的
//        allocationWrapperList.eq(ProjectAllocation::getCurrent, current);

//查询所有
        List<ProjectAllocation> accocationList = allocationService.list(allocationWrapperList);

        //查询当前确认人员角色 有可能又是项目经理又是销售负责人 还要考虑是总经理

        LambdaQueryWrapper<ProjectParticipan> personWrapper = new LambdaQueryWrapper<ProjectParticipan>();
        personWrapper.eq(ProjectParticipan::getProjectNo, projectNo);
        personWrapper.eq(ProjectParticipan::getParticipantId, userId);

        List<ProjectParticipan> list = personService.list(personWrapper);
        List<Integer> auditPost = new ArrayList<>();
        for (ProjectParticipan person : list) {
            //如果id匹配上
            if (person.getParticipantId().equals(userId)) {
                //取出岗位id
                Long postId = person.getPostId();
                auditPost.add(postId.intValue());
            }
        }

        for (ProjectAllocation allocation : accocationList) {
            List<Integer> audit = allocation.getAudit();
            if (audit == null) {
                audit = new ArrayList<>();
            }
            auditPost.addAll(audit);
            allocation.setAudit(auditPost);
        }

        boolean b = allocationService.updateBatchById(accocationList);

        LambdaQueryWrapper<AllocationDetail> detailWrapperList = new LambdaQueryWrapper<AllocationDetail>();
        detailWrapperList.eq(AllocationDetail::getProjectNo, projectNo);
//        去点阶段这个条件  因为两个阶段的绩效系数是一致的
//        detailWrapperList.eq(AllocationDetail::getCurrent, current);
        List<AllocationDetail> detailLis = detailService.list(detailWrapperList);


        for (AllocationDetail detail : detailLis) {
            detail.setAudit(auditPost);
        }

        boolean b1 = detailService.updateBatchById(detailLis);

        if (b && b1) {
            return true;
        } else {
            throw new RuntimeException("后端接口报错请联系管理员");
        }
    }


    //重新设置销售负责人的 项目提成减去其他人的
    @Override
    public void setSaleMoney(String projectNo, String current) {
        // 先使用标准岗位绩效金额 * 绩效系数 / 100  再计算其他人的金额之和  比较 谁大取谁
        //1.计算绩效
        //记录已分配的
        BigDecimal alreadyAllocationMoney = BigDecimal.ZERO;

        //查询除了销售负责人的所有岗位的绩效信息
        LambdaQueryWrapper<ProjectAllocation> allocationWrapperList = new LambdaQueryWrapper<ProjectAllocation>();
        allocationWrapperList.eq(ProjectAllocation::getProjectNo, projectNo);
        allocationWrapperList.ne(ProjectAllocation::getPostId, 5L);

        List<ProjectAllocation> accocationList = allocationService.list(allocationWrapperList);
        //循环 查询detail
        for (ProjectAllocation currAllocation : accocationList) {
            current = currAllocation.getCurrent();
            //累加其他人的已分配的  跳过销售负责人
            if (currAllocation.getPostId().equals(5L)) {
                continue;
            }

            Long id = currAllocation.getId();//父id
            LambdaQueryWrapper<AllocationDetail> detailListWrapper = new LambdaQueryWrapper<AllocationDetail>();
            detailListWrapper.eq(AllocationDetail::getAllocationId, id)
                    .eq(AllocationDetail::getCurrent, currAllocation.getCurrent());
            //查询所有该岗位下的

            List<AllocationDetail> detailLis = detailService.list(detailListWrapper);
            //累加所有的已分配的绩效金额
            for (AllocationDetail currAllocationDetail : detailLis) {
                alreadyAllocationMoney = alreadyAllocationMoney.add(currAllocationDetail.getMoney());
            }
        }
        Map<String, BigDecimal> map = accountingService.getAllList(projectNo);

        //项目提成
        BigDecimal allCommission = BigDecimal.ZERO;

        //如果是扣除质保金得出的
        if (current.equals("1")) {
            allCommission = map.get("allCommission");
        } else {
            //纯质保金部分
            allCommission = map.get("allCommissionWarranty");
        }

        BigDecimal remaining = allCommission.subtract(alreadyAllocationMoney);

        List<ProjectAllocation> allocationList = allocationService.getAllocationList(projectNo, current);
        //过滤出销售负责人  postId等于5 的
        for (ProjectAllocation currAllocation : allocationList) {
            if (currAllocation.getPostId().equals(5L)) {

                BigDecimal allocationMoney = currAllocation.getMoney();

                List<AllocationDetail> detailList = currAllocation.getDetailList();

                //销售负责人有多个的情况 平分 改为按照比例
                int count = detailList.size();
                BigDecimal result = remaining.divide(new BigDecimal(count));
                if (!detailList.isEmpty()) {
                    for (AllocationDetail saleDetail : detailList) {

                        //按比例
                        BigDecimal resultMoney = result
                                .multiply(saleDetail.getRatio())       // allCommission * ratio
                                .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);


                        saleDetail.setMoney(resultMoney);


                        //设置个人绩效
                        String personAllocation = dictDataService.selectDictLabel("allocation_type", "1");
                        BigDecimal personAllocationMoney = resultMoney.multiply(new BigDecimal(personAllocation));
                        saleDetail.setPersonMoney(personAllocationMoney);

                        //设置部门绩效
                        String deptAllocation = dictDataService.selectDictLabel("allocation_type", "2");
                        BigDecimal deptAllocationMoney = resultMoney.multiply(new BigDecimal(deptAllocation));
                        saleDetail.setDeptMoney(deptAllocationMoney);

                        detailService.updateById(saleDetail);
                    }
                }
            }
        }
        //销售负责人应该值设置一个 如果下设置多个应该去字典表再配置应该绩效分配的角色
    }

    @Override
    public void allocationDetailConfirm(AllocationDetail detail) {
        //1.获取个人本次发放金额
        BigDecimal perCurrent = detail.getPersonCurrent() != null ? detail.getPersonCurrent() : BigDecimal.ZERO;

        //2.校验本次发放和待发放
        BigDecimal perWait = detail.getWait() != null ? detail.getWait() : BigDecimal.ZERO;

        if (perCurrent.compareTo(perWait) > 0) {
            throw new RuntimeException("个人本次发放金额不能超过待发放金额");
        }

        //部门本次发放
        BigDecimal deptCurrent = detail.getDeptCurrent() != null ? detail.getDeptCurrent() : BigDecimal.ZERO;

        //校验
        //部门未发放的
        BigDecimal deptWait = detail.getDeptWait() != null ? detail.getDeptWait() : BigDecimal.ZERO;
        if (deptCurrent.compareTo(deptWait) > 0) {
            throw new RuntimeException("部门本次发放金额不能超过待发放金额");
        }

        //3.计算个人待发放金额和已发放
        //个人绩效金额
        BigDecimal personMoney = detail.getPersonMoney() != null ? detail.getPersonMoney() : BigDecimal.ZERO;
        //已发放的 需要加上本次发放
        BigDecimal personAlready = detail.getAlready() != null ? detail.getAlready() : BigDecimal.ZERO;
        personAlready = personAlready.add(perCurrent);
        detail.setAlready(personAlready);
        //待发放 = 总 - 已发放
        BigDecimal personWait = personMoney.subtract(personAlready);
        detail.setWait(personWait);

        //4.计算部门待发放和已发放
        BigDecimal deptMoney = detail.getDeptMoney() != null ? detail.getDeptMoney() : BigDecimal.ZERO;
        //已发放的 需加上本次发放
        BigDecimal deptAlready = detail.getDeptAlready() != null ? detail.getDeptAlready() : BigDecimal.ZERO;
        deptAlready = deptAlready.add(deptCurrent);
        detail.setDeptAlready(deptAlready);

        // 计算未发放金额 部门的：personMoney - already
        BigDecimal waitDept = deptMoney.subtract(deptAlready);
        // 设置回对象中
        detail.setDeptWait(waitDept);

        //比较personMoney和已发放金额是否相等(误差允许在一块钱)
        // 计算两者的差值
        BigDecimal diff = personMoney.subtract(personAlready);

        //部门部分的
        BigDecimal diffDept = deptMoney.subtract(deptAlready);

        // 判断差值是否在 [-1, 1] 范围内
        boolean isDiffWithinOneYuan = diff.abs().compareTo(BigDecimal.ONE) <= 0;


        // 判断差值是否在 [-1, 1] 范围内
        boolean isDiffWithinOneYuanDept = diffDept.abs().compareTo(BigDecimal.ONE) <= 0;

        //个人和部门都发放完成
        if (isDiffWithinOneYuan && isDiffWithinOneYuanDept) {
            // 差值在一块钱以内，视为相等
            System.out.println("金额相等（误差在1元以内）");
            detail.setConfirm("2");//已发放完成
            detail.setConfirmDate(new Date());
        } else {
            // 差异较大，需要处理
            System.out.println("金额差异超过1元");
            detail.setConfirm("1");//未发放完成
            detail.setConfirmDate(new Date());//操作时间
        }
        detailService.updateById(detail);

        // 假设 projectDetailLogs 已按时间升序排序（最早在前）

        //插入日志
        ProjectDetailLog log = new ProjectDetailLog();
        log.setProjectNo(detail.getProjectNo());
        log.setDetailId(detail.getId());
        log.setPersonName(detail.getPersonName());

        log.setPersonCurrent(detail.getPersonCurrent());
        log.setPersonTotalt(personMoney);
        log.setPersonWait(detail.getWait());

        log.setDeptCurrent(detail.getDeptCurrent());
        log.setDeptTotalt(deptMoney);
        log.setDeptWait(detail.getDeptWait());

        log.setRemark(detail.getRemark());
        log.setIssueType("1");
        log.setPersonId(detail.getPersonId());

        projectDetailLogMapper.insert(log);

    }

    @Override
    public void checkComplete(String projectNo) {
        LambdaQueryWrapper<AllocationDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AllocationDetail::getProjectNo, projectNo);
        List<AllocationDetail> list = detailService.list(queryWrapper);
        //累加个人绩效
        BigDecimal personTotal = BigDecimal.ZERO;
        //累加已发放
        BigDecimal alreadyTotal = BigDecimal.ZERO;
        for (AllocationDetail detail : list) {
            personTotal = personTotal.add(detail.getPersonMoney() != null ? detail.getPersonMoney() : BigDecimal.ZERO);
            alreadyTotal = alreadyTotal.add(detail.getAlready() != null ? detail.getAlready() : BigDecimal.ZERO);
        }


        //累加部门绩效
        BigDecimal deptTotal = BigDecimal.ZERO;
        //累加已发放的部门绩效
        BigDecimal alreadyDeptTotal = BigDecimal.ZERO;
        for (AllocationDetail detail : list) {
            deptTotal = deptTotal.add(detail.getDeptMoney() != null ? detail.getPersonMoney() : BigDecimal.ZERO);
            alreadyDeptTotal = alreadyDeptTotal.add(detail.getDeptAlready() != null ? detail.getDeptAlready() : BigDecimal.ZERO);
        }

        //比较总的个人绩效和总的已发放 是否误差在一块钱之内   部门部分的
        // 计算差值并判断是否在一块钱以内
        BigDecimal diffDept = personTotal.subtract(alreadyTotal).abs();
        boolean isWithinOneYuanDept = diffDept.compareTo(new BigDecimal("1")) <= 0;

        //比较总的个人绩效和总的已发放 是否误差在一块钱之内
        // 计算差值并判断是否在一块钱以内
        BigDecimal diff = personTotal.subtract(alreadyTotal).abs();
        boolean isWithinOneYuan = diff.compareTo(new BigDecimal("1")) <= 0;

        //还要判断是否质保阶段已完成
        LambdaQueryWrapper<ProjectPhase> projectPhaseWrapper = new LambdaQueryWrapper<>();
        projectPhaseWrapper.eq(ProjectPhase::getProjectNo, projectNo);
        projectPhaseWrapper.eq(ProjectPhase::getPhaseId, "7");
        List<ProjectPhase> phaseList = phaseService.list(projectPhaseWrapper);

        //个人绩效和部门绩效都发放完成才算完成
        if (CollectionUtils.isNotEmpty(phaseList)) {
            if (isWithinOneYuan && isWithinOneYuanDept) {
                System.out.println("总金额一致（误差在1元以内）");
                Project project = projectService.getById(projectNo);
                //更新该项目的发放状态为已发放完成
                project.setFinish(2);
                project.setConfirmDate(new Date());
                projectService.updateById(project);
            } else {
                Project project = projectService.getById(projectNo);
                //更新该项目的发放状态为已发放完成
                project.setFinish(1);
                projectService.updateById(project);
            }
        }
    }

    @Override
    public List<AllocationDetail> getStatistics() {
        //1.查分组查询出所有AllocationDetail中的项目ID
        LambdaQueryWrapper<AllocationDetail> queryWrapper = new LambdaQueryWrapper<>();
        List<AllocationDetail> detailList = baseMapper.selectList(queryWrapper);


        return List.of();
    }

    @Override
    public TableDataInfo getRank(ProjectQuery query) {
        Page<Object> page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<AllocationDetail> ranks = detailMapper.getRanks(query);
        for (int i = 0; i < ranks.size(); i++) {
            LambdaQueryWrapper<AllocationDetail> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(AllocationDetail::getPersonId, ranks.get(i).getPersonId());
            List<AllocationDetail> detailList = detailMapper.selectList(queryWrapper);
            AllocationDetail detail = ranks.get(i);
            //总的
            BigDecimal total = BigDecimal.ZERO;

            //个人总的
            BigDecimal personMoney = detail.getPersonMoney() != null ? detail.getPersonMoney() : BigDecimal.ZERO;
            //个人已发放的
            BigDecimal personAlreadyMoney = detail.getAlready() != null ? detail.getAlready() : BigDecimal.ZERO;
            detail.setAlready(personAlreadyMoney);
            //个人总的待发放的
            BigDecimal wait = personMoney.subtract(personAlreadyMoney);
            detail.setWait(wait);

            //部门总的
            BigDecimal deptMoney = detail.getDeptMoney() != null ? detail.getDeptMoney() : BigDecimal.ZERO;
            detail.setDeptMoney(deptMoney);
            //部门已发放的
            BigDecimal deptAlreadyMoney = detail.getDeptAlready() != null ? detail.getDeptAlready() : BigDecimal.ZERO;
            detail.setDeptAlready(deptAlreadyMoney);
            //部门未发放的
            BigDecimal deptWait = deptMoney.subtract(deptAlreadyMoney);
            detail.setDeptWait(deptWait);

            //未发放的
//            for (AllocationDetail detail : detailList) {
//
//            }
        }
        return new TableDataInfo(ranks, page.getTotal());
    }
}
